package cn.shop.merchant.controller.bankcard;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.shop.merchant.req.WithdrawQueryReq;
import cn.shop.merchant.req.WithdrawReq;
import cn.shop.merchant.service.BackSettingService;
import cn.shop.merchant.service.MerchantUserService;
import cn.shop.merchant.service.WithdrawService;
import cn.shop.thiredparty.service.ThiredpartyService;
import cn.shop.transcation.backSetting.entity.BackSetting;
import cn.shop.transcation.merchantUser.mapper.entity.MerchantUser;
import cn.shop.transcation.withdraw.entity.Withdraw;
import cn.shop.utils.ApiResult;
import cn.shop.utils.annotation.OperationLog;
import cn.shop.utils.constant.SMSVerificationCode;
import cn.shop.utils.enums.OperationType;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.shop.utils.constant.Constant.UID;
import static cn.shop.utils.constant.SystemSettingConstant.*;

/**
 * 提现申请接口
 *
 * @author : 李一涵
 * @date : Created in 2022-2-25 16:46
 * @description :
 */
@RestController
@RequestMapping("/withdraw")
public class WithdrawController {

    @Resource
    private WithdrawService withdrawService;
    @Resource
    private ThiredpartyService thiredpartyService;
    @Resource
    private BackSettingService settingService;
    @Resource
    private MerchantUserService merchantUserService;

    /**
     * 获取验证码
     *
     * @param phone 手机号
     * @return 返回结果
     */
    @GetMapping("getWithdrawCode")
    public ApiResult<Map<String, Object>> getPhoneCode(@RequestParam String phone) {
        String code = RandomUtil.randomNumbers(6);
        SaSession session = SaSessionCustomUtil.getSessionById(SMSVerificationCode.WITHDRAW_KEY + phone);
        session.set("code", code);
        session.updateTimeout(300);
        thiredpartyService.sendSms(code, 5, phone);
        return ApiResult.success("验证码发送成功!");
    }

    /**
     * 提现申请
     *
     * @param req 申请信息
     * @return 返回结果
     */
    @PostMapping("")
    @OperationLog(desc = "提现", type = OperationType.CREATE)
    public ApiResult<Map<String, Object>> withdraw(@Validated @RequestBody WithdrawReq req) {
        long uid = StpUtil.getSession().getLong(UID);
        SaSession session = SaSessionCustomUtil.getSessionById(SMSVerificationCode.WITHDRAW_KEY + req.getMobile());
        if (session == null) {
            return ApiResult.fail("验证码错误");
        }
        String code = (String) session.get("code");
        if (!StrUtil.equalsIgnoreCase(code, req.getCode())) {
            return ApiResult.fail("验证码错误");
        }
        MerchantUser user = merchantUserService.getById(uid);
        if (StrUtil.isBlank(user.getTransactionPassword())) {
            return ApiResult.fail("请设置交易密码", null);
        }
        session.logout();
        Map<String, String> range = withdrawService.withdrawRange();
        String min = range.get(WITHDRAW_MIN), max = range.get(WITHDRAW_MAX);
        if (NumberUtil.isNumber(min) && NumberUtil.isGreater(new BigDecimal(min), req.getAmount())) {
            return ApiResult.fail("提现金额不能低于" + min + "元");
        }
        if (NumberUtil.isNumber(max) && NumberUtil.isLess(new BigDecimal(max), req.getAmount())) {
            return ApiResult.fail("提现金额不能超过" + max + "元");
        }
        LocalDate now = LocalDate.now();
        BackSetting setting = settingService.findByKey(WITHDRAW_DAY_COUNT);
        long times = NumberUtil.parseInt(setting.getValue());
        if (times > 0) {
            long count = withdrawService.count(Wrappers.<Withdraw>lambdaQuery()
                    .eq(Withdraw::getUserId, user.getId())
                    .apply("date_format (create_time,'%Y-%m-%d') >= {0}", now)
                    .apply("date_format (create_time,'%Y-%m-%d') <= {0}", now));
            if (count >= times ) {
                return ApiResult.fail("今日已提现"+count+"次，已达上限");
            }
        }
        return withdrawService.withdraw(uid, req.getAmount(), req.getId(), req.getType(), req.getPassword());
    }

    /**
     * 提现记录
     *
     * @param req 查询条件
     * @return 返回结果
     */
    @GetMapping("")
    public ApiResult<Map<String, Object>> list(@Validated WithdrawQueryReq req) {
        Map<String, Object> data = withdrawService.listPage(StpUtil.getSession().getLong(UID), req);
        return ApiResult.success(data);
    }

    /**
     * 查看可提现范围
     * @return 返回结果
     */
    @GetMapping("/range")
    public ApiResult<Map<String, String>> range() {
        return ApiResult.success(withdrawService.withdrawRange());
    }
}
